%%% @author Viktor Green <viktor@student.gu.se>
%%% @copyright (C) 2011, Viktor Green
%%% @doc
%%% Module to handle torrent files, reading/parsing and extracting
%%% values from the parsed file
%%% @end
%%% Created : 19 Oct 2011 by Viktor Green <viktor@student.gu.se>

-module(torrent_file).

-export([parse/1,get_value/2]).

%%--------------------------------------------------------------------
%% @doc
%% Parse a torrent-file into erlang terms
%% @end
%%--------------------------------------------------------------------
-spec parse(File :: string()) -> {ok, bencode:b_term()} |
				 {error, Reason :: term()}.
parse(File) ->
    case file:read_file(File) of
	{ok, Binary} ->
	    try {ok, bencode:decode(Binary)}
	    catch
		error:Reason -> {error, Reason}
	    end;
	{error, Reason} ->
	    {error, Reason}
    end.

%%--------------------------------------------------------------------
%% @doc
%% Get a specific value from a parsed torrent file
%% @end
%%--------------------------------------------------------------------
-spec get_value(Req :: string(), bencode:b_dictionary()) ->
		       bencode:b_term() |
		       {error, Reason :: term(), not_found}.
get_value(String, {dictionary, [{{string, String}, Data} | _Tail]})  ->
    Data;
get_value(Req, {dictionary, [_Head | Tail]}) ->
    get_value(Req, {dictionary, Tail});
get_value(_Req, {dictionary, []}) ->
    {error, not_found}.
